<?php
declare(strict_types=1);

namespace app\controller\user;

use app\BaseController;
use app\model\{ExpressServiceProvider, ExpressPriceCache};
use app\service\Kuaidi100Service;
use think\facade\{Cache, Log};
use think\Request;

class ExpressController extends BaseController
{
    /**
     * 获取快递公司列表
     */
    public function companies()
    {
        $list = ExpressServiceProvider::where('status', 1)
            ->field('id, company_name, company_code, logo, service_type, description')
            ->order('id', 'asc')
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 运费预估
     */
    public function estimate(Request $request)
    {
        $data = $this->validate($request->post(), [
            'company_code' => 'require',
            'from_province' => 'require',
            'from_city' => 'require',
            'to_province' => 'require',
            'to_city' => 'require',
            'weight' => 'require|float|>:0',
            'insure_amount' => 'float|>=:0'
        ]);
        
        try {
            // 获取快递服务商
            $express = ExpressServiceProvider::where('company_code', $data['company_code'])
                ->where('status', 1)
                ->find();
                
            if (!$express) {
                throw new \Exception('快递公司不存在或已禁用');
            }
            
            // 从缓存获取价格
            $cacheKey = "express_price:{$data['company_code']}:{$data['from_province']}:{$data['from_city']}:{$data['to_province']}:{$data['to_city']}";
            $price = Cache::get($cacheKey);
            
            if (!$price) {
                // 从数据库获取价格
                $price = ExpressPriceCache::where([
                    'express_service_provider_id' => $express->id,
                    'from_province' => $data['from_province'],
                    'from_city' => $data['from_city'],
                    'to_province' => $data['to_province'],
                    'to_city' => $data['to_city']
                ])->find();
                
                if (!$price) {
                    // 调用快递100获取价格
                    $kuaidi100 = new Kuaidi100Service();
                    $price = $kuaidi100->queryPrice([
                        'com' => $data['company_code'],
                        'from' => $data['from_province'] . $data['from_city'],
                        'to' => $data['to_province'] . $data['to_city'],
                        'weight' => $data['weight']
                    ]);
                    
                    // 缓存价格
                    if ($price) {
                        ExpressPriceCache::create([
                            'express_service_provider_id' => $express->id,
                            'from_province' => $data['from_province'],
                            'from_city' => $data['from_city'],
                            'to_province' => $data['to_province'],
                            'to_city' => $data['to_city'],
                            'first_price' => $price['first_price'],
                            'continued_price' => $price['continued_price'],
                            'create_time' => date('Y-m-d H:i:s')
                        ]);
                        
                        Cache::set($cacheKey, $price, 3600); // 缓存1小时
                    }
                }
            }
            
            // 计算运费
            $fee = $this->calculateFee($express, $price, $data);
            
            return $this->success('获取成功', $fee);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 计算运费
     */
    protected function calculateFee($express, $price, $data)
    {
        $weight = $data['weight'];
        $fee = [
            'base' => 0,    // 基础运费
            'insure' => 0,  // 保价费
            'total' => 0    // 总费用
        ];
        
        // 首重费用
        if ($weight <= 1) {
            $fee['base'] = $price['first_price'];
        } else {
            // 续重费用
            $fee['base'] = $price['first_price'] + 
                ceil($weight - 1) * $price['continued_price'];
        }
        
        // 保价费
        if (!empty($data['insure_amount']) && $data['insure_amount'] > 0) {
            $fee['insure'] = ceil($data['insure_amount'] * $express->insure_rate);
        }
        
        // 计算总费用
        $fee['total'] = $fee['base'] + $fee['insure'];
        
        return $fee;
    }
} 